import  {  NextRequest, NextResponse } from 'next/server'
import { NextApiRequest, NextApiResponse } from "next";
import { getIronSession  } from "iron-session"; //缓存
import { ironOptions } from "config/index"; //缓存配置
import { cookies } from 'next/headers';
import { Cookie } from 'next-cookie'
import {setCookie} from 'utils/index'
import { prepareConnection } from 'db/index'
import { User, UserAuth } from 'db/entity/index'

// 解决ts报错
interface a {
  userId:number
  avatar:string
  nickname:string
  save(): unknown
  verifyCode: number
}

type a1 =  NextApiRequest & NextRequest
type a2 =  NextApiResponse & NextResponse

export const POST =  async ( req:a1 ,res:a2 ) =>{
  const { phone='',verify='',identity_type='phone'} = await req.json()
  console.log('Cookie=>',Cookie)
  const cookiedata = Cookie.fromApiRoute(req,res)
  console.log('cookiedata=>',cookiedata)
  // 控制台有报错
  const db = await prepareConnection()
  const userAuthRepo = db.getRepository(UserAuth)
  try {
    const session = await getIronSession(cookies(),ironOptions) as a;
    console.log('session',session)
    // const { phone='',verify='',identity_type='phone'} = await req.body
    if(Number(verify) === session.verifyCode){
      // 验证码正确
      // 查询数据库是否存在数据
      const userAuth = await userAuthRepo.findOne(
        {
          identity_type,
          identifier: phone
        },
        // 关系型查找
        {relations:['user']}
        )
      if(userAuth){
        // 已注册
        const user = userAuth.user
        const {id,nickname,avatar} = user
        session.userId = id
        session.nickname = nickname
        session.avatar = avatar
        await session.save()
        return  NextResponse.json({msg:'登录成功',code:0,data:{ userId:id ,nickname,avatar}},{status:200})
      }else{
        // 新用户、自动注册
        const user = new User()
        user.nickname = `用户_${Math.floor(Math.random() * 1000)}`
        user.avatar = './images/avatar.jpg'
        user.job = '暂无'
        user.introduce = '暂无'
        // 另外一张表
        const userAuth = new UserAuth()
        userAuth.identifier = phone
        userAuth.identity_type = identity_type
        userAuth.credential = String(session.verifyCode)
        userAuth.user = user
        // 保存数据
        const resUserAuth = await userAuthRepo.save(userAuth)
        const {user:{id,nickname,avatar}} = resUserAuth
        session.userId = id
        session.nickname = nickname
        session.avatar = avatar
        await session.save()
        // setCookie(cookie,{id,avatar,nickname})
        return  NextResponse.json({msg:'登录成功',code:0,data:{ userId:id ,nickname,avatar}},{status:200})
      }
     
    }else{
      return  NextResponse.json({msg:'登录失败，验证码不正确',code:500},{status:200})
    }
  } catch (error) {
    return  NextResponse.json({msg:error,code:501},{status:200})
  }
}